package com.itboye.ihomebank.activity.hetong;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.qianyue.fragment.OrderFragment;
import com.itboye.ihomebank.adapter.HeTongAdapter;
import com.itboye.ihomebank.adapter.ListAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.HeTongBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.db.HeTongDBManager;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.CaculateYearAndMonth;
import com.itboye.ihomebank.util.DayCountTwo;
import com.itboye.ihomebank.util.FuKuanFangShiPopupWindow;
import com.itboye.ihomebank.util.MyGongJv;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.itboye.ihomebank.util.YuYueChooseTimePopwindow;
import com.itboye.ihomebank.widget.wheelview.WheelView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * 填写合同
 */
public class TianXieHeTongActivityFangDong extends BaseOtherActivity implements
        Observer , YuYueChooseTimePopwindow.onFinishedLisenter {
    View v_statusbar;
    ListView listView;
    UserPresenter userPresenter;
    TextView add_shap_title_tv;
    LinearLayout li_container;
    Button tijiao;
    private int selectStartYear;
    private int selectEndYear;

    private int selectStartMonth;
    private int selectEndMonth;
    ArrayList<TextView> devices = new ArrayList<>();
    int index;
    Calendar dateAndTime = Calendar.getInstance(Locale.CHINA);
    private String uid;
    private String contractNo;
    ArrayList<View> views = new ArrayList<>();//用来存申城json的key，传到后台
    ArrayList<EditText> editTexts = new ArrayList<>();//将所有的编辑框放进集合
    private String selectDevice;
    private String selectFeiYong;
    private String unselectFeiYong;
    protected int qishu;
    protected String yajin;
    Calendar current = Calendar.getInstance();
    protected FuKuanFangShiPopupWindow mCameraPopupWindow;
    private  PopupWindow rentUsePop;
    String fukuanfangshi = "";
    protected TextView yuefu;
    protected TextView eryuefu;
    protected TextView jifu;
    protected TextView bannianfu;
    protected TextView nianfu;
    protected TextView yicixingfu;
    ImageView close_icon;

    List<HeTongBean> datas;
    ListView rent_list;//租聘用途的list
    private ArrayList<String> options1ItemsUse = new ArrayList<>();//租赁
    private OptionsPickerView pvOptionsUse;

    private String money;
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.tijiao:
                buildJson();// 生成json数据
                break;

            default:
                break;
        }
    }

    public void buildJson() {
        Gson gson = new Gson();
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < views.size(); i++) {
            EditText editText = (EditText) views.get(i).findViewById(R.id.edit);

            if (views.get(i).getTag().equals("rent_info")) {// 房租信息
                if (zujinxinxi.equals("")){
                    ByAlert.alert("请填写房租信息");
                    return;
                }
                map.put(editText.getTag() + "", zujinxinxi);
            } else if (views.get(i).getTag().equals("renter_fee_items")) {
                TextView textView = (TextView) views.get(i).findViewById(
                        R.id.txt_device);
                map.put(editText.getTag() + "", textView.getText().toString());
            } else if (views.get(i).getTag().equals("sign_leaser")) {
                if (imgId.equals("")){
                    ByAlert.alert("您还没有签名");
                    return;
                }
                map.put(editText.getTag() + "", imgId);
            } else if (views.get(i).getTag().equals("lessor_fee_items")) {
                TextView textView = (TextView) views.get(i).findViewById(
                        R.id.txt_device);
                map.put(editText.getTag() + "", textView.getText().toString());
            } else if (views.get(i).getTag().equals("facility")) {
                map.put(editText.getTag() + "", ((TextView) views.get(i)
                        .findViewById(R.id.txt_device)).getText().toString());
            } else if (views.get(i).getTag().equals("pay_before_day")) {
                EditText te = (EditText) views.get(i).findViewById(R.id.edit);
                map.put(editText.getTag() + "", te.getText().toString());
                if(te.getText().toString().equals("")) {
                    ByAlert.alert("请填写下期房租提前支付天数");
                    return;
                }
                if(!te.getText().toString().equals("")){
                    if (Double.parseDouble(te.getText().toString()) > 31) {
                        ByAlert.alert("天数不能大于31");
                        return;
                    }
                }
            } else if (views.get(i).getTag().equals("is_stage")) {
                EditText te = (EditText) views.get(i).findViewById(R.id.edit);
                map.put(editText.getTag() + "", te.getText().toString().equals("是")?"1":"0");
            } else if (views.get(i).getTag().equals("is_bank_stage")) {
                EditText te = (EditText) views.get(i).findViewById(R.id.edit);
                 //银行分期 样式 1年 分11期 分5*2期  半年 分5期
                if (te.getText().toString().trim().equals("是")){
                    if (money.equals("合同期一年,用户分11期")||money.equals("合同期半年,用户分5期")){
                        map.put(editText.getTag() + "","1");
                    }else if (money.equals("合同期一年,用户半年分两次5期")){
                        map.put(editText.getTag() + "","1,2");
                    }
                }else {
                    map.put(editText.getTag() + "","0");
                }
            }else {
                if (!views.get(i).getTag().equals("other_note")){
                    EditText te = (EditText) views.get(i).findViewById(R.id.edit);
                    if (te.getText().toString().equals("")) {
                        ByAlert.alert("请填写详细信息");
                        return;
                    }
                }

                map.put(editTexts.get(i).getTag() + "", editTexts.get(i)
                        .getText().toString());
            }
        }
        String jsonStr = gson.toJson(map);
        HeTongDBManager dbManager = new HeTongDBManager(this);
        long re = dbManager.addNote(uid, contractNo, "lesser", jsonStr);
        if (re > 0) {
            ByAlert.alert("添加成功" + contractNo);
        } else {
            ByAlert.alert("添加失败");
        }

        userPresenter.tiJiaoHeTong(uid, contractNo, jsonStr);
        System.out.println("》》生成的json字符串" + jsonStr);
    }

    @Override
    protected int layout_id() {
        // TODO Auto-generated method stub
        return R.layout.activity_hetong;
    }

    @Override
    protected void onInitController() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onInit() {
        // TODO Auto-generated method stub
        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("填写合同");
        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
        contractNo = getIntent().getStringExtra("contractNo");
        userPresenter = new UserPresenter(this);
        userPresenter.heTongParams("0", contractNo);
        options1ItemsUse.add("办公");
        options1ItemsUse.add("居住");
    }

    @Override
    protected void onReadIntent(Bundle bundle) {
        // TODO Auto-generated method stub

    }

    String textStringStart = "";
    String textStringEnd = "";

    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.heTongParams_success) {
                datas = (List<HeTongBean>) entity.getData();
                HeTongAdapter adapter = new HeTongAdapter(this, datas,
                        R.layout.item_hetong);
                for (int i = 0; i < datas.size(); i++) {
                    final HeTongBean bean = datas.get(i);
                    Integer inputType = bean.getValueType();// 5、整型 1、字符串 4、日期
                    // 0、点击进去 2、签字

                    final View view = LayoutInflater.from(this).inflate(
                            R.layout.item_hetong, null);
                    TextView txt_device = (TextView) view
                            .findViewById(R.id.txt_device);
                    devices.add(txt_device);
                    TextView text = (TextView) view.findViewById(R.id.txt);
                    final EditText editText = (EditText) view.findViewById(R.id.edit);
                    switch (inputType) {// 1: 文本、2: 图片、3: 当前时间 4：当前日期 5：数字 ,默认0
                        case 1:
                     //       editText.setInputType(InputType.TYPE_CLASS_TEXT);
                            break;
                        case 2:

                            break;
                        case 3:

                            break;
                        case 4:

                            break;
                        case 5:
                            if (!bean.getKey().equals("water_meter_reading") && !bean.getKey().equals("gas_reading") && !bean.getKey().equals("electric_instrument_reading")) {
                                editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                            }
                            break;

                        default:
                            break;
                    }
                    editText.setTag(bean.getKey());
                    editText.setHint(bean.getDesc());
                    if (!bean.get_default().equals("")) {//当默认值不为空的时候，设置不可以输入
                        editText.setEnabled(false);
                        editText.setText(bean.get_default());
                    }

                    if(bean.getKey().equals("rent_use")){//租聘用途
                        editText.setEnabled(false);
                        editText.setText(bean.get_default());
                    }
                    if (bean.getKey().equals("start_date")
                            || bean.getKey().equals("end_date")
                            || bean.getKey().equals("rent_info")|| bean.getKey().equals("is_stage")||bean.getKey().equals("is_bank_stage")) {//结束时间，开始时间，租金的时候，设置不可以编辑
                        editText.setEnabled(false);
                    }
                    if (bean.getKey().equals("sign_leaser")
                            || bean.getKey().equals("lessor_fee_items")
                            || bean.getKey().equals("renter_fee_items")
                            || bean.getKey().equals("facility")
                            || bean.getKey().equals("pay_type")) {//甲方签字日期，租赁期间由甲方承担费用项目，租赁期间由乙方承担费用项目，资产清单，付款方式   设置不可以编辑
                        editText.setEnabled(false);
                    }
                    if (bean.getKey().equals("sign_leaser_date")) {//甲方签字日期，设置为今天
                        editText.setText(current.get(Calendar.YEAR)
                                + "-"
                                + ((current.get(Calendar.MONTH) + 1) + "-" + current
                                .get(Calendar.DATE)));
                        editText.setEnabled(false);
                    }
                    if (bean.getKey().equals("other_note")) {//其他约定，设置可以输入，
                        editText.setEnabled(true);
                        editText.setMaxLines(3);
                    }
                    //隐藏掉 小额贷款 和银行分期
                    if (bean.getKey().equals("is_bank_stage")){
                        view.setVisibility(View.GONE);
                    }
                    if (bean.getKey().equals("is_stage")) {
                        view.setVisibility(View.GONE);
                    }

                    editTexts.add(editText);// 将所有的编辑框放进集合

                    text.setText(bean.getAlias());
                    li_container
                            .addView(view, li_container.getChildCount() - 1);
                    view.setTag(datas.get(i).getKey() + "");
                    views.add(view);
                    view.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            if ((v.getTag() + "").equals("people_number")){//居住人数
                                resetEdettextFocus(editText);
                            }

                            if ((v.getTag() + "").equals("pay_before_day")){//下期房租提前支付天数
                                resetEdettextFocus(editText);
                            }
                            if ((v.getTag() + "").equals("break_month")){//违约金为_个月租金
                                resetEdettextFocus(editText);
                            }

                            if ((v.getTag() + "").equals("other_note")){//其他约定
                                resetEdettextFocus(editText);
                            }

                            if ((v.getTag() + "").equals("facility")) {// 资产清单
                                Intent intent = new Intent(
                                        TianXieHeTongActivityFangDong.this,
                                        ActivityTianXieHeTongThree.class);
                                startActivityForResult(intent, 101);
                            }
                            if ((v.getTag() + "").equals("lessor_fee_items")
                                    || (v.getTag() + "")
                                    .equals("renter_fee_items")) {//租赁期间由甲方承担费用项目,租赁期间由乙方承担费用项目
                                Intent intent = new Intent(
                                        TianXieHeTongActivityFangDong.this,
                                        ActivityFeiYongFenTan.class);
                                startActivityForResult(intent, 103);
                            }
                            if ((v.getTag()+"").equals("rent_use")){//租聘用途
                                EditText viewById = (EditText) v.findViewById(R.id.edit);
                                initOptionPicker(viewById);
                                pvOptionsUse.show();
//                                showZuPinPop(viewById);

                            }
                            if ((v.getTag() + "").equals("sign_leaser")) {// 甲方签字
                                Intent intent = new Intent(
                                        TianXieHeTongActivityFangDong.this,
                                        ActivityHuaBan.class);
                                startActivityForResult(intent, 107);
                            }

                            if ((v.getTag() + "").equals("pay_type")) {//付款方式
                                MyGongJv.yincang(v);
                                mCameraPopupWindow = new FuKuanFangShiPopupWindow(
                                        TianXieHeTongActivityFangDong.this,
                                        this);
                                mCameraPopupWindow.showAtLocation(v,
                                        Gravity.BOTTOM
                                                | Gravity.CENTER_HORIZONTAL, 0,
                                        0);
                                yuefu = (TextView) mCameraPopupWindow
                                        .getContentView().findViewById(
                                                R.id.yuefu);
                                yuefu.setOnClickListener(fuKuanListener);
                                eryuefu = (TextView) mCameraPopupWindow
                                        .getContentView().findViewById(
                                                R.id.eryuefu);
                                eryuefu.setOnClickListener(fuKuanListener);
                                jifu = (TextView) mCameraPopupWindow
                                        .getContentView().findViewById(
                                                R.id.jifu);
                                jifu.setOnClickListener(fuKuanListener);
                                bannianfu = (TextView) mCameraPopupWindow
                                        .getContentView().findViewById(
                                                R.id.bannianfu);
                                bannianfu.setOnClickListener(fuKuanListener);
                                nianfu = (TextView) mCameraPopupWindow
                                        .getContentView().findViewById(
                                                R.id.nianfu);
                                nianfu.setOnClickListener(fuKuanListener);
                                yicixingfu = (TextView) mCameraPopupWindow
                                        .getContentView().findViewById(
                                                R.id.yicixingfu);
                                yicixingfu.setOnClickListener(fuKuanListener);
                            }

                            if ((v.getTag() + "").equals("rent_info")) { //租金
                                if (fukuanfangshi.equals("")) {
                                    ByAlert.alert("请先选择付款方式");
                                    return;
                                }
                                for (View editText : views) {
                                    if (editText.getTag().toString().equals("deposit")) {
                                        if (((EditText) editText.findViewById(R.id.edit)).getText().toString().equals("")) {
                                            ByAlert.alert("请先输入预付押金");
                                            return;
                                        }
                                        yajin = ((EditText) editText.findViewById(R.id.edit)).getText().toString();
                                    }
                                }
                                if (textStringEnd.equals("")|| textStringStart.equals("")) {
                                    ByAlert.alert("请先选择起租或止租日期");
                                    return;
                                }
                                if ((CaculateYearAndMonth
                                        .parseDate(textStringEnd) - CaculateYearAndMonth
                                        .parseDate(textStringStart)) <= 0) {
                                    ByAlert.alert("起租年月应小于止租年月");
                                    return;
                                }
                                if ((selectEndYear - selectStartYear) > 5) {
                                    ByAlert.alert("最大止租为5年");
                                    return;
                                }
                                String tempDate = "";
                                tempDate = DayCountTwo.remainDateToString(
                                        textStringStart, textStringEnd);
                                String tempMonth = tempDate.split("-")[1];
                                String tempDay = tempDate.split("-")[2];
                                qishu = Integer.parseInt(tempDate.split("-")[0]);// 获取年份
                                if (fukuanfangshi.equals("月付")) {
                                    if (qishu <= 0&& Integer.parseInt(tempMonth.equals("") ? "0": tempMonth) < 1) {
                                        ByAlert.alert("付款方式为[" + fukuanfangshi+ "],租期至少为一个月");
                                        return;
                                    }
                                }
                                if (fukuanfangshi.equals("二月付")) {
                                    if (qishu <= 0&& Integer.parseInt(tempMonth.equals("") ? "0": tempMonth) < 2) {
                                        ByAlert.alert("付款方式为[" + fukuanfangshi+ "],租期至少为二个月");
                                        return;
                                    }
                                }
                                if (fukuanfangshi.equals("季付")) {
                                    if (qishu <= 0&& Integer.parseInt(tempMonth.equals("") ? "0": tempMonth) < 4) {
                                        ByAlert.alert("付款方式为[" + fukuanfangshi
                                                + "],租期至少为四个月");
                                        return;
                                    }
                                }
                                if (fukuanfangshi.equals("半年付")) {
                                    if (qishu <= 0&& Integer.parseInt(tempMonth.equals("") ? "0": tempMonth) < 6) {
                                        ByAlert.alert("付款方式为[" + fukuanfangshi+ "],租期至少为六个月");
                                        return;
                                    }
                                }
                                if (fukuanfangshi.equals("年付")) {
                                    if (qishu <= 0) {
                                        ByAlert.alert("付款方式为[" + fukuanfangshi
                                                + "],租期至少为一年");
                                        return;
                                    }

                                }
                                if (fukuanfangshi.equals("一次性付")) {
                                    if (qishu <= 0&& Integer.parseInt(tempMonth.equals("") ? "0": tempMonth) < 1) {
                                        ByAlert.alert("付款方式为[" + fukuanfangshi
                                                + "],租期至少为一个月");
                                        return;
                                    }
                                }
                                if(qishu==0){
                                    qishu = 1;
                                }else{
                                    if (Integer.parseInt(tempMonth) > 0
                                            || Integer.parseInt(tempDay) > 0) {
                                        qishu += 1;
                                    }
                                }
                                String type="1";//标记是否含有“is_stage”字段，没有type=1 表示没有分期，有type=2 表示有分期
                                String bankType="1";//标记是否含有“is_bank_stage”字段，bankType不为空或者0 表示有分期
                                for (int j = 0; j < datas.size(); j++) {
                                    if (datas.get(j).getKey().equals("is_stage")){
                                        type="2";
                                        break;
                                    }
                                }

                                Intent intent = new Intent(
                                        TianXieHeTongActivityFangDong.this,
                                        ActivityEditFangZuXinXi.class);
                                intent.putExtra("yajin", yajin);
                                intent.putExtra("totalDate", tempDate);
                                intent.putExtra("qishu", qishu);
                                intent.putExtra("type", type);
                                intent.putExtra("contractNo", contractNo);
                                startActivityForResult(intent, 105);

                            }
                            if ((v.getTag() + "").equals("deposit")) {

                            }
                            if ((v.getTag() + "").equals("start_date")) {
                                MyGongJv.yincang(v);
                                if (fukuanfangshi.equals("")) {
                                    ByAlert.alert("请先选择付款方式");
                                    return;
                                }
                                YuYueChooseTimePopwindow endTimePopwindow = new YuYueChooseTimePopwindow(
                                        TianXieHeTongActivityFangDong.this, TianXieHeTongActivityFangDong.this, true);
                                endTimePopwindow.getContentView().findViewById(R.id.time).setVisibility(View.GONE);
                                endTimePopwindow.getContentView().findViewById(R.id.min).setVisibility(View.GONE);
                                endTimePopwindow.showAtLocation(v, Gravity.BOTTOM
                                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                            }
                            if ((v.getTag() + "").equals("end_date")) {
                                MyGongJv.yincang(v);
                                if (fukuanfangshi.equals("")) {
                                    ByAlert.alert("请先选择付款方式");
                                    return;
                                }
                                if (textStringStart.equals("")) {
                                    ByAlert.alert("请先选择开始时间");
                                    return;
                                }
                                YuYueChooseTimePopwindow endTimePopwindow = new YuYueChooseTimePopwindow(
                                        TianXieHeTongActivityFangDong.this, TianXieHeTongActivityFangDong.this, false);
                                endTimePopwindow.getContentView().findViewById(R.id.time).setVisibility(View.GONE);
                                endTimePopwindow.getContentView().findViewById(R.id.min).setVisibility(View.GONE);
                                endTimePopwindow.showAtLocation(v, Gravity.BOTTOM
                                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                            }
                        }
                    });
                }
                listView.setAdapter(adapter);
            } else if (entity.getEventType() == UserPresenter.heTongParams_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.heTongTiJiao_success) {
                Intent intent = new Intent();
                intent.putExtra("shenfen", "lesser");
                intent.putExtra("contractNo", contractNo);
                sendBroadcast(intent);
                OrderFragment.getInstance().refresh();
                ByAlert.alert(entity.getData());
                finish();
            } else if (entity.getEventType() == UserPresenter.heTongTiJiao_fail) {
                ByAlert.alert(entity.getData());
            }
        }
    }

    // 当点击DatePickerDialog控件的设置按钮时，调用该方法
    DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // 修改日历控件的年，月，日
            // 这里的year,monthOfYear,dayOfMonth的值与DatePickerDialog控件设置的最新值一致
            dateAndTime.set(Calendar.YEAR, year);
            dateAndTime.set(Calendar.MONTH, monthOfYear);
            dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            // 将页面TextView的显示更新为最新时间
            for (View v : views) {
                TextView text = (TextView) v.findViewById(R.id.txt_device);
                if (v.getTag().toString().equals("start_date")) {
                    updateLabel(text);
                }
                if (v.getTag().toString().equals("end_date")) {
                    v.findViewById(R.id.txt_device).setVisibility(View.VISIBLE);
                    ((TextView) v.findViewById(R.id.txt_device))
                            .setText(selectFeiYong);
                    updateLabel(text);
                }
            }

        }
    };
    private String zujinxinxi="";
    private String imgId="";


    //view 点击 editext 获取焦点软键盘弹出
    private void setEditextFocus(EditText text){


    }
    // 更新页面TextView的方法
    private void updateLabel(TextView dateAndTimeLabel) {
        dateAndTimeLabel.setVisibility(View.VISIBLE);
        dateAndTimeLabel.setText(TimesUtils.timeDate(Long.parseLong(dateAndTime
                .getTime().toString())));

    }
    //让edittext 方便获取焦点（点击父类parentview 让edittext 获取焦点并弹出软键盘）

    public void resetEdettextFocus(EditText editText){
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        //打开软键盘
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 102) {
            if (data != null) {
                selectDevice = data.getStringExtra("selectDevice");
                for (View v : views) {
                    if (v.getTag().toString().equals("facility")) {
                        v.findViewById(R.id.txt_device).setVisibility(
                                View.VISIBLE);
                        ((TextView) v.findViewById(R.id.txt_device))
                                .setText(selectDevice);
                    }
                }
            }
        }
        if (requestCode == 103 && resultCode == 104) {
            selectFeiYong = data.getStringExtra("select");
            unselectFeiYong = data.getStringExtra("unselect");
            for (View v : views) {
                if (v.getTag().toString().equals("renter_fee_items")) {
                    v.findViewById(R.id.txt_device).setVisibility(View.VISIBLE);
                    ((TextView) v.findViewById(R.id.txt_device))
                            .setText(selectFeiYong);
                }
                if (v.getTag().toString().equals("lessor_fee_items")) {
                    v.findViewById(R.id.txt_device).setVisibility(View.VISIBLE);
                    ((TextView) v.findViewById(R.id.txt_device))
                            .setText(unselectFeiYong);
                }
            }
        }

        if (requestCode == 105 && resultCode == 106) {//从租金跳转回来
            zujinxinxi = data.getStringExtra("zujinxinxi");
            String fenqi= data.getStringExtra("fenqi");
            String bank= data.getStringExtra("bank");
            for (View v : views) {
                if (v.getTag().toString().equals("rent_info")) {
                    v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
                    ((EditText) v.findViewById(R.id.edit)).setText("已填写");
                }
                if (v.getTag().toString().equals("is_bank_stage")){
                    v.setVisibility(View.GONE);
                    ((EditText) v.findViewById(R.id.edit)).setText(bank);
                }

                if (fenqi.equals("是")){ //当有分期的时候
                    if (v.getTag().toString().equals("is_stage")) {
                        v.setVisibility(View.VISIBLE);
                        v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
                        ((EditText) v.findViewById(R.id.edit)).setText(fenqi);
                    }

                    if (v.getTag().toString().equals("pay_type")) {//当有分期的时候，付款方式默认为“月付”
                        v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
                        ((EditText) v.findViewById(R.id.edit)).setText("月付");
                    }

                    if (v.getTag().toString().equals("end_date")) {//当有分期的时候，结束的月份为开始月份的一年后的前一天
                        int year = Integer.parseInt(textStringStart.split("-")[0]);// 获取年份
                        int mouth = Integer.parseInt(textStringStart.split("-")[1]);// 获取月份
                        int day = Integer.parseInt(textStringStart.split("-")[2]);// 获取日期
                        Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
                        ca.set(year, mouth-1, day);//月份是从0开始的，所以11表示12月
                        ca.add(Calendar.YEAR, +1);
                        ca.add(Calendar.DATE, -1);
                        Date lastMonth = ca.getTime(); //结果
                        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                        ((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
                    }
                }else { //没有小贷分期
                    if (v.getTag().toString().equals("is_stage")) {
                        v.setVisibility(View.GONE);
                        v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
                        ((EditText) v.findViewById(R.id.edit)).setText(fenqi);
                    }

                }
            }
        }

        if (requestCode == 105 && resultCode == 110) {//银行分期 从租金跳转回来
            money= data.getStringExtra("date");
            String bank= data.getStringExtra("bank");
            String fenqi= data.getStringExtra("fenqi");
            zujinxinxi = data.getStringExtra("zujinxinxi");
//            options1ItemsZhiFu.add("分11期");
//            options1ItemsZhiFu.add("分5*2期");
//            options1ItemsZhiFu.add("分5期");
//            if (zujinxinxi.equals("分11期")){
//
//            }else if (zujinxinxi.equals("分5*2期")){
//
//            }else if (zujinxinxi.equals("分5期")){
//
//            }
            for (View v : views) {
                if (v.getTag().toString().equals("is_stage")) {
                    v.setVisibility(View.GONE);
                    v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
                    ((EditText) v.findViewById(R.id.edit)).setText(fenqi);
                }

                if (v.getTag().toString().equals("rent_info")) {
                    v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
                    ((EditText) v.findViewById(R.id.edit)).setText("已填写");
                }

//                if (v.getTag().toString().equals("is_stage")) {
//                    v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
//                    ((EditText) v.findViewById(R.id.edit)).setText("否");
//                }
                if (bank.equals("是")){ //当有银行分期的时候
                    if (v.getTag().toString().equals("is_bank_stage")){
                        v.setVisibility(View.VISIBLE);
                        ((EditText) v.findViewById(R.id.edit)).setText(bank);
                    }
                    if (v.getTag().toString().equals("pay_type")) {//当有银行分期的时候
                        v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
                        ((EditText) v.findViewById(R.id.edit)).setText("月付");
                    }

                    if (v.getTag().toString().equals("end_date")) {//当有分期的时候，结束的月份为开始月份的一年后的前一天
                        int startYear = Integer.parseInt(textStringStart.split("-")[0]);// 获取年份
                        int startMouth = Integer.parseInt(textStringStart.split("-")[1]);// 获取月份
                        int startDay = Integer.parseInt(textStringStart.split("-")[2]);// 获取日期
                        int endYear = Integer.parseInt(textStringEnd.split("-")[0]);// 获取年份
                        int endMouth = Integer.parseInt(textStringEnd.split("-")[1]);// 获取月份
                        int endDay = Integer.parseInt(textStringEnd.split("-")[2]);// 获取日期
                        if (money.equals("合同期一年,用户分11期")||money.equals("合同期一年,用户半年分两次5期")){
                            Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
                            ca.set(startYear, startMouth-1, startDay);//月份是从0开始的，所以11表示12月
                            ca.add(Calendar.YEAR, +1);
                            ca.add(Calendar.DATE, -1);
                            Date lastMonth = ca.getTime(); //结果
                            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                            ((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
                        }else if (money.equals("合同期半年,用户分5期")){
                            Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
                            ca.set(startYear, startMouth-1, startDay);//月份是从0开始的，所以11表示12月
                            ca.add(Calendar.DATE, -1);
                            ca.add(Calendar.MONTH,6);//改变成6个月
                            Date lastMonth = ca.getTime(); //结果
                            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                            ((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
                        }

//                        if (endYear>startYear){
//                            if (endMouth-startMouth>=0){//大于1年
//                                Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
//                                ca.set(startYear, startMouth-1, startDay);//月份是从0开始的，所以11表示12月
//                                ca.add(Calendar.YEAR, +1);
//                                ca.add(Calendar.DATE, -1);
//                                Date lastMonth = ca.getTime(); //结果
//                                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//                                ((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
//                            }else {//小于一年
//                                Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
//                                ca.set(startYear, startMouth-1, startDay);//月份是从0开始的，所以11表示12月
//                                ca.add(Calendar.DATE, -1);
//                                ca.add(Calendar.MONTH,6);//改变成6个月
//                                Date lastMonth = ca.getTime(); //结果
//                                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//                                ((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
//                            }
//                        }else {
//                            if (endMouth-startMouth>=5){//小于1年
//                                Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
//                                ca.set(startYear, startMouth-1, startDay);//月份是从0开始的，所以11表示12月
//                                ca.add(Calendar.DATE, -1);
//                                ca.add(Calendar.MONTH,6);//改变成6个月
//                                Date lastMonth = ca.getTime(); //结果
//                                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//                                ((EditText) v.findViewById(R.id.edit)).setText(sf.format(lastMonth));
//                            }
//
//                        }

                    }
                }else { //没有银行分期
                    if (v.getTag().toString().equals("is_bank_stage")){
                        v.setVisibility(View.GONE);
                        ((EditText) v.findViewById(R.id.edit)).setText(bank);
                    }
                }
            }
        }

        if (requestCode == 107 && resultCode == 108) {// 上传签字图片
            imgId = data.getStringExtra("imgId");
            for (View v : views) {
                if (v.getTag().toString().equals("sign_leaser")) {
                    v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
                    ((EditText) v.findViewById(R.id.edit)).setText("已签名");
                }
            }
        }

    }
    protected OnClickListener fuKuanListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.yuefu:
                    fukuanfangshi = "月付";
                    mCameraPopupWindow.dismiss();
                    break;
                case R.id.eryuefu:
                    fukuanfangshi = "二月付";
                    mCameraPopupWindow.dismiss();
                    break;
                case R.id.jifu:
                    fukuanfangshi = "季付";
                    mCameraPopupWindow.dismiss();
                    break;
                case R.id.bannianfu:
                    fukuanfangshi = "半年付";
                    mCameraPopupWindow.dismiss();
                    break;
                case R.id.nianfu:
                    fukuanfangshi = "年付";
                    mCameraPopupWindow.dismiss();
                    break;
                case R.id.yicixingfu:
                    fukuanfangshi = "一次性付";
                    mCameraPopupWindow.dismiss();
                    break;
            }
            for (int i = 0; i < editTexts.size(); i++) {
                if (editTexts.get(i).getTag().equals("pay_type")) {
                    editTexts.get(i).setText(fukuanfangshi);
                }

                for (int j = 0; j < datas.size(); j++) {
                    if (datas.get(j).getKey().equals("is_stage")){
                        if (!fukuanfangshi.equals("月付")){//如果已经选择填了资金，如果选择的不是“月付”，资金和填写分期设为空
                            zujinxinxi="";
                            if (editTexts.get(i).getTag().equals("is_stage")){
                                if (!editTexts.get(i).getText().toString().equals("")){
                                    ByAlert.alert("日期重新选择，请重新填写租金");
                                    if (editTexts.get(i).getTag().equals("is_stage")) {
                                        editTexts.get(i).setText("");
                                    }
                                }
                            }
                            if (editTexts.get(i).getTag().equals("rent_info")){
                                if (!editTexts.get(i).getText().toString().equals("")){
                                    if (editTexts.get(i).getTag().equals("rent_info")) {
                                        editTexts.get(i).setText("");
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }
    };
    @Override
    public void getBeginTime(String year, String month, String day, String hour, String minite) {
        textStringStart = year + "-" + month + "-" + day ;
        for (View v : views) {
            if (v.getTag().toString().equals("start_date")) {
                ((EditText) v
                        .findViewById(R.id.edit))
                        .setText(textStringStart);
                ((EditText) v
                        .findViewById(R.id.edit))
                        .setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void getEndTime(String year, String month, String day, String hour, String minite) {
        textStringEnd = year + "-" + month + "-" + day ;
        for (View v : views) {
            if (v.getTag().toString().equals("end_date")) {
                ((EditText) v.findViewById(R.id.edit)).setText(textStringEnd);
                ((EditText) v.findViewById(R.id.edit)).setVisibility(View.VISIBLE);
            }
            for (int j = 0; j < datas.size(); j++) {
                if (datas.get(j).getKey().equals("is_stage")){
                    int years = Integer.parseInt(textStringStart.split("-")[0]);// 获取年份
                    int mouths = Integer.parseInt(textStringStart.split("-")[1]);// 获取月份
                    int days = Integer.parseInt(textStringStart.split("-")[2]);// 获取日期
                    Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
                    ca.set(years, mouths-1, days);//月份是从0开始的，所以11表示12月
                    ca.add(Calendar.YEAR, +1);
                    ca.add(Calendar.DATE, -1);
                    Date lastMonth = ca.getTime(); //结果
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                    String time=sf.format(lastMonth);

                    int yearss = Integer.parseInt(time.split("-")[0]);// 获取年份
                    int mouthss = Integer.parseInt(time.split("-")[1]);// 获取月份
                    int dayss = Integer.parseInt(time.split("-")[2]);// 获取日期

                    int yearsss = Integer.parseInt(year);// 获取年份
                    int mouthsss = Integer.parseInt(month);// 获取月份
                    int daysss = Integer.parseInt(day);// 获取日期

                    System.out.println("ssssssss>"+"yearss-->"+yearss+"...mouthss"+mouthss+"...dayss"+dayss+".swr..yearsss"+yearsss+"...mouthsss"+mouthsss+"...daysss"+daysss);
                    if (yearss!=yearsss||mouthss!=mouthsss||dayss!=daysss){
                        zujinxinxi="";
                        if (v.getTag().toString().equals("is_stage")){
                            ((EditText) v.findViewById(R.id.edit)).setText("");
                        }
                        if (v.getTag().toString().equals("rent_info")){
                            ((EditText) v.findViewById(R.id.edit)).setText("");
                        }
                    }
                    break;
                }
            }
        }
    }

    //租聘用途

    /**
     * 支付方式
//     */
    private void initOptionPicker(final EditText text) {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */
        text.setFocusable(false);
        pvOptionsUse = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1ItemsUse.get(options1);
                text.setText(tx);
            }
        })
                .setTitleText("租赁用途")
                .setContentTextSize(16)//设置滚轮文字大小
                .setTitleSize(16)//设置标题文字大小
                .setSubCalSize(16)//设置确定按钮大小
                .setSelectOptions(0, 1)//默认选中项
                .setLineSpacingMultiplier(2.0f)//设置间距倍数,但是只能在1.2-2.0f之间
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setBgColor(Color.WHITE)//滚轮背景颜色
                .setTitleBgColor(Color.WHITE)//标题背景颜色
                .setTitleColor(Color.BLACK)//标题颜色
                .setCancelColor(Color.BLACK)//取消按钮颜色
                .setSubmitColor(Color.BLACK)//确定按钮颜色
                .setTextColorCenter(Color.BLACK)//分割线之间的文字颜色
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setLabels("", "", "")
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        pvOptionsUse.setPicker(options1ItemsUse);//二级选择器
    }

    public void showZuPinPop(final EditText text){

        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_rentuse, null);
//        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_houseuse, null);
        rentUsePop=new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
//        rentUsePop.setAnimationStyle(R.style.popupwindow_anim_style);
        //passwordpop 可点击
        rentUsePop.setFocusable(true);

        TextView title= (TextView) contentView.findViewById(R.id.rent_title);
        TextView cancel = (TextView) contentView.findViewById(R.id.rent_cancle);
        rent_list= (ListView) contentView.findViewById(R.id.rent_list);
        final String [] rentArray=new String[]{"办公","商用"};
        ListAdapter listAdapter = new ListAdapter(this, rentArray);
        rent_list.setAdapter(listAdapter);
        contentView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId()== R.id.rent_title){

                }else {
                    rentUsePop.dismiss();
                }
            }
        });

        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                rentUsePop.dismiss();
            }
        });
         rent_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 text.setText(rentArray[position]);
                 rentUsePop.dismiss();
             }
         });

//        //新的租聘用途
//        TextView cancel = (TextView) contentView.findViewById(R.id.user_cancel);
//        TextView sure = (TextView) contentView.findViewById(R.id.user_ok);
//        WheelView wheelView = (WheelView) contentView.findViewById(R.id.userUse);


        contentView.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        contentView.setFocusableInTouchMode(true); //comment by danielinbiti,设置view能够接听事件 标注2
//        //点击手机返回键pop关闭
//        contentView.setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//                if (keyCode==KeyEvent.KEYCODE_BACK){
//                    if (rentUsePop!=null){
//                        rentUsePop.dismiss();
//                        currentIndex=-1;
//                    }
//
//                }
//                return false;
//            }
//        });

        rentUsePop.showAtLocation(contentView,Gravity.BOTTOM,0,0);

    }
}
